//
//  HouseListViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/9/21.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "HouseListViewController.h"
#import "RentVieitor.h"
#import "RentOptionView.h"
#import "AllHouseCell.h"
#import "HouseDetailViewController.h"
#import "FangModel.h"
#import "MJRefresh.h"

@interface HouseListViewController ()<LiaoRentDeleget,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>


@end

@implementation HouseListViewController{
    
    UITableView *_tableview;
    NSString *_identify;
    RentOptionView *optinView;
    NSString *rent_start;//最小租金
    NSString *rent_end;//最大租金'
    NSString *bedroom;//卧室数量
    NSString *characteristic;//特色
    NSString *district;//区域
    NSInteger page;//页码
    NSString *title;//搜索关键字
    UITextField *field;
    NSArray *moneyStart;
    NSArray *moneyEnd;
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.data = [NSMutableArray array];
    self.view.backgroundColor = BackgroundColor;
    self.title = @"租房";
    page = 1;
    moneyStart = @[@"",@"1",@"3000",@"4000",@"5000",@"6000",@"7000",@""];
    moneyEnd = @[@"",@"3000",@"4000",@"5000",@"6000",@"7000",@"10000",@""];
    [self creatLeftView];
    [self creatView];
    [self reloadData];
    [self creatNavigationView];
}


- (void)creatNavigationView {
    
    //搜索视图
    UIView *naView = [[UIView alloc] init];
    naView.layer.masksToBounds = YES;
    naView.layer.cornerRadius = 5;
    naView.backgroundColor = [UIColor whiteColor];
    naView.layer.borderWidth = 1;
    naView.layer.borderColor = [Utils colorConvertFromString:@"#999999"].CGColor;
    naView.frame = CGRectMake(30, 60, KWidth-70, 30);
    
    //    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    selectBtn.frame = CGRectMake(0,0, 70, 30);
    //    selectBtn.tag = 100;
    //    selectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    //    [selectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 30)];
    //    [selectBtn setImageEdgeInsets:UIEdgeInsetsMake(5, 40, 0, 0)];
    //    [selectBtn setTitleColor:[Utils colorConvertFromString:@"#101010"] forState:UIControlStateNormal];
    //    [selectBtn setTitle:@"深圳" forState:UIControlStateNormal];
    //    //    [selectBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [selectBtn setImage:[UIImage imageNamed:@"三角形"] forState:UIControlStateNormal];
    //    [naView addSubview:selectBtn];
    
    field = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, naView.frame.size.width-60, 30)];
    field.delegate = self;
    field.font = [UIFont systemFontOfSize:14];
    field.leftViewMode = UITextFieldViewModeAlways;
    [naView  addSubview:field];
    field.placeholder = @"请输入小区名称或者地址";
    self.navigationItem.titleView = naView;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 15)];
    UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    [leftView addSubview:imgview];
    imgview.image = [UIImage imageNamed:@"搜索icon"];
    field.leftView = leftView;
}


- (void)creatLeftView {
    
//    // 自定义导航栏左侧按钮
//    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    leftBtn.frame = CGRectMake(0, 0, 10,20 );
//    [leftBtn setBackgroundImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
//    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 20, 20);
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"搜索icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

- (void)creatView {
    
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, KWidth, KHeight-40) style:UITableViewStylePlain];
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview .showsHorizontalScrollIndicator = NO;
    _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _identify = @"_Cell";
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KWidth*200/750)];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KWidth*200/750)];
    [view addSubview:imgView];
    imgView.image = [UIImage imageNamed:@"rent_heard"];
    _tableview.tableHeaderView = view;

    
    [self.view addSubview:_tableview];
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh)];
    [_tableview registerClass:[AllHouseCell class] forCellReuseIdentifier:_identify];
    
    optinView = [[RentOptionView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 40) deleget:self];
    [optinView becomeFirstResponder];
    [self.view addSubview:optinView];
    
}

- (void)reloadData {
    
    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    page = 1;
    if (bedroom == nil) {
        bedroom = @"";
    }
    if (district == nil) {
        district = @"";
    }
    if (characteristic == nil) {
        characteristic = @"";
    }
    if (rent_start == nil) {
        rent_start = @"";
    }
    if (rent_end == nil) {
        rent_end = @"";
    }
    if (title == nil) {
        title = @"";
    }
    NSString *url = [NSString stringWithFormat:@"%@fang/list",Main_Url];
    NSDictionary *dic = @{
                          @"category":@"1001",
                          @"city":@"103",
                          @"bedroom":bedroom,
                          @"district":district,
                          @"characteristic":characteristic,
                          @"rent_start":rent_start,
                          @"rent_end":rent_end,
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          @"title":title
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                
                FangModel *model = [[FangModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [WeakSelf.data addObject:model];
            }
            
            [_tableview   reloadData];
            [_tableview.mj_header endRefreshing];
            if (WeakSelf.data.count == 10) {
                page ++;
            }
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        [_tableview.mj_header endRefreshing];
    }];
    
}

//下拉刷新
- (void)headerRefresh {
    
    
    bedroom = @"";
    district = @"";
    characteristic = @"";
    rent_start = @"";
    rent_end = @"";
    title = @"";
    
    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    [self reloadData];
    //    __weak typeof(self)WeakSelf = self;
    //    NSString *url = [NSString stringWithFormat:@"%@fang/list",Main_Url];
    //    NSDictionary *dic = @{
    //                          @"category":@"1001",
    //                          @"city":@"103",
    //                          @"bedroom":bedroom,
    //                          @"district":district,
    //                          @"characteristic":characteristic,
    //                          @"rent_start":rent_start,
    //                          @"rent_end":rent_end,
    //                          @"page":[NSString stringWithFormat:@"%ld",page]
    //                          };
    //    NSString *str = [ReturnSign returnSignWithDic:dic];
    //    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    //
    //    //32位小写
    //
    //    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //    //                          NSUTF8StringEncoding];
    //
    //    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    //    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    //    [param setObject:md5String forKey:@"sign"];
    //    //    [param setValue:md5String forKey:@"sign"];
    //
    //    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
    //
    //
    //        if ([response[@"code"] isEqualToString:@"10000"]) {
    //
    //            NSArray *dataArray = response[@"data"];
    //            for (NSDictionary *dic in dataArray) {
    //
    //                FangModel *model = [[FangModel alloc] init];
    //                [model setValuesForKeysWithDictionary:dic];
    //                [WeakSelf.data addObject:model];
    //            }
    //
    //            [_tableview   reloadData];
    //            [_tableview.mj_header endRefreshing];
    //        }
    //
    //
    //    } failure:^(NSError *err) {
    //
    //
    //    }];
    
}

- (void)footRefresh {
    page ++;
    __weak typeof(self)WeakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@fang/list",Main_Url];
    NSDictionary *dic = @{
                          @"category":@"1001",
                          @"city":@"103",
                          @"bedroom":bedroom,
                          @"district":district,
                          @"characteristic":characteristic,
                          @"rent_start":rent_start,
                          @"rent_end":rent_end,
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          @"title":title
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSArray *dataArray = response[@"data"];
            if (dataArray.count <10) {
                page --;
            }
            for (NSDictionary *dic in dataArray) {
                
                FangModel *model = [[FangModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [WeakSelf.data addObject:model];
            }
            
            [_tableview   reloadData];
            [_tableview.mj_footer endRefreshing];
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        page --;
        
    }];
    
    //    __weak typeof(self)WeakSelf = self;
    [_tableview.mj_footer endRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AllHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:_identify forIndexPath:indexPath];
    
    if (self.data.count > indexPath.row) {
        cell.model = self.data[indexPath.row];
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 170*Main_Scale;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HouseDetailViewController *detailVc = [[HouseDetailViewController alloc] init];
    if (self.data.count > indexPath.row) {
        FangModel *model = self.data[indexPath.row];
        detailVc.sn = model.sn;
    }
    
    [self.navigationController pushViewController:detailVc animated:YES];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [field endEditing:YES];
}

- (void)liaoOptionView:(RentOptionView *)option select:(NSString *)select index:(NSInteger)index {
    
    //    optinView.frame = CGRectMake(0, 0, KWidth, KHeight);
    if ( index == 100) {
        
        district = select;
    }else if(index == 101) {
        
        NSInteger selectIndex = [select integerValue];
        rent_start = moneyStart[selectIndex];
        rent_end = moneyEnd[selectIndex];
    }else if(index == 102) {
        
        bedroom = select;
    }else if(index == 103) {
        characteristic = select;
    }
}

- (void)liaoOptionView:(RentOptionView *)option changeFrame:(BOOL)isChange {
    
    if (isChange == YES) {
        optinView.frame = CGRectMake(0, 0, KWidth, 40);
    }else {
        optinView.frame = CGRectMake(0, 0, KWidth, KHeight);
    }
}


//- (void)backAction {
//    
//    [self.navigationController popViewControllerAnimated:YES];
//}

- (void)searchAction {
    
    title = field.text;
//    optinView.frame = CGRectMake(0, 0, KWidth, 40);
    [self reloadData];
}
@end
